package com.dailyblue.java.spring.consumer.service.impl;

import com.dailyblue.cloud.bookstore.commons.util.JsonResult;
import com.dailyblue.java.spring.consumer.service.Consumer8001Service;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
public class Consumer8001ServiceImpl implements Consumer8001Service {
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;
    private Integer index = 0;

    @Override
    public JsonResult a() {
        // 获取到所有的demo(服务的提供者)实例
        List<ServiceInstance> list = discoveryClient.getInstances("demo");
        // http://localhost:8011
        // 轮询方案
        String uri = list.get(index).getUri() + "/demo";
        JsonResult result = restTemplate.getForObject(uri, JsonResult.class);
        if (index < list.size() - 1) {
            index++;
        } else {
            index = 0;
        }

        return result;
    }

    @Override
    public JsonResult b(String name) {
        // 获取到所有的demo(服务的提供者)实例
        List<ServiceInstance> list = discoveryClient.getInstances("demo");
        // 随机方案
        int random = (int) (Math.random() * list.size());
        // http://localhost:8011
        String uri = list.get(random).getUri() + "/demo/" + name;
        JsonResult result = restTemplate.getForObject(uri, JsonResult.class);
        return result;
    }

    @Override
    public JsonResult c() {
        return restTemplate.getForObject("http://demo/demo", JsonResult.class);
    }

    @Override
    public JsonResult d(String name) {
        return restTemplate.getForObject("http://demo/demo/" + name, JsonResult.class);
    }


    public JsonResult c1(){
        return restTemplate.getForObject("http://demo/demo/c",JsonResult.class);
    }

    public JsonResult d1(){
        return restTemplate.getForObject("http://demo/demo/d",JsonResult.class);
    }
    public JsonResult e1(){
        return restTemplate.getForObject("http://demo/demo/e",JsonResult.class);
    }

}
